<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="bean名" prop="beanName">
        <el-input
          v-model="queryParams.beanName"
          placeholder="请输入bean名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="jobStatus">
        <el-select v-model="queryParams.jobStatus" placeholder="请选择" size="small" clearable>
          <el-option :key="0" label="停止" :value="0" />
          <el-option :key="1" label="启用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          v-hasPermission="['system:job:add']"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="jobList">
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="bean名" prop="beanName" align="center" show-overflow-tooltip />
      <el-table-column label="方法名" prop="methodName" align="center" show-overflow-tooltip />
      <el-table-column label="方法参数" prop="methodParams" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.methodParams === ''|| scope.row.methodParams === null || scope.row.methodParams === undefined ? '---' : scope.row.methodParams }}
        </template>
      </el-table-column>
      <el-table-column label="cron表达式" prop="cronExpression" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <span>
              {{ (scope.row.cronExpression) }}
            </span>
            <div slot="content">{{ parseCron(scope.row.cronExpression) }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="jobStatus" label="任务状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.jobStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="立即执行" placement="top">
            <i class="el-icon-video-play" style="cursor: pointer;margin-right: 5%" v-hasPermission="['system:job:execute']" @click="handleExcuse(scope.row)" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <i class="el-icon-edit" style="cursor: pointer;margin-right: 5%" v-hasPermission="['system:job:update']" @click="handleUpdate(scope.row)" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="el-icon-delete" style="cursor: pointer" v-hasPermission="['system:job:delete']" @click="handleDelete(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :current-page.sync="queryParams.pageNum"
      @current-change="getList"
      @size-change="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body @before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="bean名字" prop="beanName">
              <el-input v-model="form.beanName" placeholder="请输入bean名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方法名" prop="methodName">
              <el-input v-model="form.methodName" placeholder="请输入方法名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="方法参数" prop="methodParams">
              <el-input v-model="form.methodParams" placeholder="请输入方法参数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态" prop="jobStatus">
              <el-select v-model="form.jobStatus" placeholder="请选择" style="width: 100%">
                <el-option :key="0" label="停止" :value="0" />
                <el-option :key="1" label="启用" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-popover v-model="cronPopover" placement="top-start">
                <cron
                  @change="onChangeCron"
                  @close="onCloseCron"
                />
                <el-input
                  slot="reference"
                  v-model="form.cronExpression"
                  :value="form.cronExpression"
                  placeholder="请输入定时策略"
                  @click="cronPopover = true"
                />
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="5%">
              <span v-if="cronMean!==''" class="cron-mean-span">cron意思：{{ cronMean }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import {addJob, deleteJobById, executeJob, getJobById, listJob, updateJob, updateJobStatus} from '@/api/system/job'
import { cron } from 'vue-cron'
import { parseCron } from '@/utils/sg'
export default {
  name: 'Job',
  components: { cron },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beanName: null,
        jobStatus: undefined
      },
      total: 0,
      // 表单参数
      form: {
        beanName: '',
        methodParams: '',
        methodName: null,
        remark: '',
        cronExpression: '',
        jobStatus: undefined
      },
      // 表单校验
      rules: {
        beanName: [{ required: true, trigger: 'blur', message: '请输入bean名' }],
        methodName: [{ required: true, trigger: 'blur', message: '请输入方法名' }],
        jobStatus: [{ required: true, trigger: 'blur', message: '请选择任务状态' }],
        cronExpression: [{ required: true, trigger: 'blur', message: '请选择cron表达式' }],
        remark: [{ required: true, trigger: 'blur', message: '请输入备注' }]
      },
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      jobList: [],
      cronPopover: false
    }
  },
  computed: {
    cronMean() {
      if (this.form.cronExpression) {
        return parseCron(this.form.cronExpression)
      }
      return ''
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleQuery() {
      this.getList()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加任务'
    },
    handleUpdate(item) {
      getJobById(item.jobId).then((res) => {
        this.form = res
        this.open = true
        this.title = '修改任务'
      })
    },
    handleDelete(item) {
      const ids = item.jobId
      this.$modal
        .confirm('是否确认删除id为' + ids + '的数据项？')
        .then(function() {
          return deleteJobById(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handleExcuse(item) {
      const loading = this.$loading({
        lock: true,
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      executeJob(item).then(() => {
        loading.close()
        this.$message.success('任务调用完成')
      }).catch(() => {
        loading.close()
      })
    },
    onChangeCron(val) {
      this.form.cronExpression = val.substring(0, val.length - 2)
    },
    onCloseCron() {
      this.cronPopover = false
    },
    handleStatusChange(item) {
      updateJobStatus(item).then(() => {
        this.$message.success('修改成功')
        this.getList()
      })
    },
    reset() {
      this.form = {
        beanName: '',
        methodParams: '',
        methodName: null,
        remark: '',
        cronExpression: '',
        jobStatus: undefined
      }
    },
    submitForm() {
      this.$refs['form'].validate((valid, error) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在执行中......',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          if (this.form.jobId !== undefined) {
            updateJob(this.form).then(() => {
              loading.close()
              this.$message.success('更新成功')
              this.open = false
              this.getList()
            }).catch(() => {
              loading.close()
            })
          } else {
            addJob(this.form).then(() => {
              loading.close()
              this.$message.success('保存成功')
              this.open = false
              this.getList()
            }).catch(() => {
              loading.close()
            })
          }
        } else {
          return
        }
      })
      this.open = false
      this.reset()
    },
    cancel() {
      this.open = false
      this.reset()
    },
    getList() {
      this.loading = true
      listJob(this.queryParams).then(res => {
        this.loading = false
        this.jobList = res.rows
        this.total = res.total
      })
    }
  }
}
</script>

<style scoped>

  .cron-mean-span {
    width: 100%;
    display: inline-block;
    line-height: initial;
  }
</style>
